<?php

class YandexService extends Auth
{
    public $clientId='';
    public $clientSecret='';
    protected $token='';
    protected $userInfo=false, $serviceName='yandex';

    public function getUserInfo()
    {
        $info=$this->userInfo;

        $names=isset($info->real_name) ? explode(' ',$info->real_name) : false;
        return array(
            'user'=>array(
                'login'=>isset($info->display_name) ? $info->display_name : '',
                'userName'=>isset($info->display_name) ? $info->display_name : '',
                'password'=>'',
                'confirmCode'=>'',
                'email'=>isset($info->default_email) ? $info->default_email : (isset($info->emails) && is_array($info->emails) ? $info->emails[0] : ''),
                'isConfirmed'=>1,
                'isActive'=>1,
            ),
            'profile'=>array(
                'firstName'=>$names && isset($names[1]) ? $names[1] : '',
                'lastName'=>$names && isset($names[0]) ? $names[0] : '',
                'sex'=>$info->sex!==null ? $info->sex : 0,
                'img'=>'',
                'birthday'=>isset($info->birthday) ? $info->birthday : NULL,
            ),
        );
    }

    public function getToken()
    {
        return $this->token;
    }

    public function getServiceName()
    {
        return $this->serviceName;
    }

    public function firstRequest()
    {
        $redirectUrl='https://oauth.yandex.ru/authorize?response_type=code&client_id='.$this->clientId;
        Yii::app()->request->redirect($redirectUrl);
    }

    public function secondRequest()
    {
        if($code=Yii::app()->request->getQuery('code')){
            try{
                $bodyParams='grant_type=authorization_code&code='.$code.
                    '&client_id='.$this->clientId.
                    '&client_secret='.$this->clientSecret;

                $post=Yii::app()->post->open('https://oauth.yandex.ru/token','curl',443);
                $post->body=$bodyParams;
                if($post->sendRequest() && $this->token=$post->result->access_token){
                    $redirectUrl='https://login.yandex.ru/info?format=json&oauth_token='.$this->token;
                    if(is_object($request=json_decode(file_get_contents($redirectUrl)))){
                        $this->userInfo=$request;
                        return true;
                    }
                }else{
                    $this->quit('Не удалось отправить POST-запрос: '.$post->error);
                }
            }catch(Exception $e){
                echo $e; exit;
            }
        }

        return false;
    }
}